import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 明确的用户字段，避免嵌套
    id: '',          // 用户ID
    username: '',    // 用户名
    nickname: '',    // 昵称
    email: '',       // 邮箱
    role: '',        // 角色（admin/normal）
    token: localStorage.getItem('token') || '',  // token
    isLoggedIn: false  // 登录状态
  }),
  
  getters: {
    // 简化：直接访问明确的字段，无需复杂判断
    showName: (state) => state.nickname || state.username,  // 优先显示昵称
    isAdmin: (state) => state.role === 'admin'
  },
  
  actions: {
    // 登录：直接赋值明确的字段
    login(userData, token) {
      this.id = userData.id || ''
      this.username = userData.username || ''
      this.nickname = userData.nickname || ''
      this.email = userData.email || ''
      this.role = userData.role || ''
      this.token = token
      this.isLoggedIn = true
      localStorage.setItem('token', token)
    },
    
    // 更新用户信息（部分字段）
    updateInfo(partialData) {
      Object.keys(partialData).forEach(key => {
        if (this.hasOwnProperty(key)) {  // 只更新state中已定义的字段
          this[key] = partialData[key]
        }
      })
    },
    
    // 退出登录：清空所有字段
    logout() {
      this.id = ''
      this.username = ''
      this.nickname = ''
      this.email = ''
      this.role = ''
      this.token = ''
      this.isLoggedIn = false
      localStorage.removeItem('token')
    }
  }
})